package com.rjs.serialization;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.rjs.serialization.constant.SerializeType;

public class SerializerEngine {

	public static final Map<SerializeType, ISerializer> serializerMap = new ConcurrentHashMap<SerializeType, ISerializer>();
	
	static {
		serializerMap.put(SerializeType.DefaultJavaSerializer, new DefaultSerializer());
		serializerMap.put(SerializeType.HessianSerializer, new HessianSerializer());
		serializerMap.put(SerializeType.JSONSerializer, new JSONSerializer());
		serializerMap.put(SerializeType.MarshallingSerializer, new MarshallingSerializer());
		serializerMap.put(SerializeType.ProtoStuffSerializer, new ProtoStuffSerializer());
		serializerMap.put(SerializeType.XmlSerializer, new XmlSerializer());
	}
	
	public static <T> byte[] serialize(T obj, String serializeType) {
		SerializeType serialize = SerializeType.queryByType(serializeType);
		if (serialize == null) {
			throw new RuntimeException("serialize is null");
		}
		ISerializer serializer = serializerMap.get(serialize);
		if (serializer == null) {
			throw new RuntimeException("serialize error");
		}
		try {
			return serializer.serialize(obj);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public static <T> T deserialize(byte[] buf, Class<T> clzz, String serializeType) {
		SerializeType serialize = SerializeType.queryByType(serializeType);
		if (serialize == null) {
			throw new RuntimeException("serialize is null");
		}
		ISerializer serializer = serializerMap.get(serialize);
		if (serializer == null) {
			throw new RuntimeException("serialize error");
		}
		try {
			return serializer.deserialize(buf, clzz);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
